#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {

    Node* cur = head;
    while (cur)
    {
        Node* newhead = (Node*)malloc(sizeof(Node));
        newhead->val = cur->val;
        newhead->next = cur->next;
        newhead->random = NULL;
        cur->next = newhead;
        cur = newhead->next;
    }
    cur = head;
    while (cur)
    {
        Node* copy = cur->next;
        if (cur->random == NULL)
        {
            copy->random = NULL;
        }
        else
        {
            copy->random = cur->random->next;
        }
        cur = copy->next;
    }
    cur = head;
    Node* copyhead = NULL;
    Node* copytail = NULL;
    while (cur)
    {
        Node* copy = cur->next;
        Node* next = copy->next;
        if (copytail == NULL)
        {
            copyhead = copytail = copy;
        }
        else
        {
            copytail->next = copy;
            copytail = copytail->next;
        }
        cur->next = next;
        cur = next;
    }
    return copyhead;
}

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* detectCycle(struct ListNode* head) {
    struct ListNode* fast = head;
    struct ListNode* slow = head;
    while (fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;
        if (fast == slow)
        {
            struct ListNode* meet = slow;
            fast = head;
            while (meet != fast)
            {
                meet = meet->next;
                fast = fast->next;
            }
            return meet;
        }

    }
    return NULL;
}